package com.juguo.charginganimation.View.activity;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.fenghuajueli.lib_ad.AdConfig;
import com.fenghuajueli.lib_ad.AdShowUtils;
import com.google.gson.Gson;
import com.juguo.charginganimation.Bean.BaseBean;
import com.juguo.charginganimation.BuildConfig;
import com.juguo.charginganimation.Data.ApiAddress;
import com.juguo.charginganimation.Data.remote.RetrofitManager;
import com.juguo.charginganimation.MainActivity;
import com.juguo.charginganimation.MainApplication;
import com.juguo.charginganimation.R;
import com.juguo.charginganimation.repository.PixabayService;
import com.juguo.charginganimation.utils.DeviceIdUtil;
import com.juguo.charginganimation.utils.RxUtils;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;


public class CsjSplashActivity extends Activity {
    private static final String TAG = "SplashActivity";
    private FrameLayout mSplashContainer;
    //是否强制跳转到主页面
    private boolean mForceGoMain;

    //是否是第一次使用
    private boolean isFirstUse;
    //开屏广告加载超时时间,建议大于3000,这里为了冷启动第一次加载到广告并且展示,示例设置了3000ms
    private static final int AD_TIME_OUT = 5000;
    private String mCodeId = ApiAddress.CSJ_CODE_ID;
    private boolean mIsExpress = false; //是否请求模板广告
    private CompositeDisposable mDisposable = new CompositeDisposable();

    @SuppressWarnings("RedundantCast")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_splash);
        super.onCreate(savedInstanceState);
        mSplashContainer = (FrameLayout) findViewById(R.id.fl_ad);
        initViewAndData();

    }


    private void showPrivacyDialog() {
        //NONE 无  CSJ 穿山甲  SYS 自系统
//        boolean isAgree = (boolean) mySharedPreferences.getValue("isagree", false);
        //判断首次启动app
        SharedPreferences preferences = getSharedPreferences("isFirstUse", MODE_PRIVATE);
        SharedPreferences.Editor edit = preferences.edit();
        isFirstUse = preferences.getBoolean("isFirstUse", false);
        if (isFirstUse) {
            showAd();
            return;
        }
        LinearLayout relativeLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.dialog_agree, null);
        Button bt_cancel = (Button) relativeLayout.findViewById(R.id.bt_cancle);
        Button bt_sure = (Button) relativeLayout.findViewById(R.id.bt_sure);
        TextView tv_message = (TextView) relativeLayout.findViewById(R.id.tv_message);

        String userLicenseAgreement = "《用户协议》";
        String privacyAgreement = "《隐私政策》";
        String message = "本公司非常重视您的隐私保护和个人信息保护，在您使用产品前，请务必认真阅读并了解";
        String messageAll = "本公司非常重视您的隐私保护和个人信息保护，在您使用产品前，请务必认真阅读并了解"
                + userLicenseAgreement + "和" + privacyAgreement
                + "全部条款，您同意并接受全部协议条款后方可使用我们提供的服务";

        int start_User = message.length();
        int end_User = start_User + userLicenseAgreement.length() - 1;
        int start_Privacy = end_User + 3;
        int end_Privacy = start_Privacy + privacyAgreement.length() - 1;

        final SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
        spannableStringBuilder.append(messageAll);
        ClickableSpan userLicenseClickableSpan = new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                Intent userLicenseIntent = new Intent(CsjSplashActivity.this, UserAgreementActivity.class);
                userLicenseIntent.putExtra("url", "file:///android_asset/web/UserLicenseAgreement.html");
                startActivity(userLicenseIntent);
                finish();
            }
        };
        ClickableSpan privacyClickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                Intent userLicenseIntent = new Intent(CsjSplashActivity.this, PrivacyPolicysActivity.class);
                userLicenseIntent.putExtra("url", "file:///android_asset/web/PrivacyPolicys.html");
                startActivity(userLicenseIntent);
                finish();
            }
        };

        spannableStringBuilder.setSpan(userLicenseClickableSpan, start_User, end_User, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableStringBuilder.setSpan(privacyClickableSpan, start_Privacy, end_Privacy, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        tv_message.setMovementMethod(LinkMovementMethod.getInstance());
        tv_message.setText(spannableStringBuilder);

        AlertDialog dialog = new AlertDialog.Builder(this)
                .setView(relativeLayout)
                .setCancelable(false)
                .create();
        dialog.setView(relativeLayout, 0, 0, 0, 0);
        dialog.show();

        //放在show()之后，不然有些属性是没有效果的，比如height和width
        Window dialogWindow = dialog.getWindow();
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        // 设置宽度
        p.width = (int) (d.getWidth() * 0.95); // 宽度设置为屏幕的0.95
        p.gravity = Gravity.CENTER;//设置位置
        //p.alpha = 0.8f;//设置透明度
        dialogWindow.setAttributes(p);

        bt_cancel.setOnClickListener(v -> {
            dialog.dismiss();
            finish();
        });
        bt_sure.setOnClickListener(v -> {
            edit.putBoolean("isFirstUse", true).apply();
//            checkPermission();
            Requestlogin();
            dialog.dismiss();
            ThirdPartySdk();
            showAd();
        });
    }

    public void ThirdPartySdk() {
        //强烈建议在应用对应的Application#onCreate()方法中调用，避免出现content为null的异常
        AdConfig config = new AdShowUtils.AdConfigBuilder()
                .setAdAppId(ApiAddress.CSJ_APP_ID)
                .setSplashId(ApiAddress.CSJ_CODE_ID)
                .setInteractionExpressId(ApiAddress.CSJ_CHAP_ID)
                .builder();
        AdShowUtils.getInstance().initAdConfig(MainApplication.getsInstance(), BuildConfig.DEBUG, config);
    }


    private void showAd() {
        if (MainApplication.getsInstance().isShowAd) {
            hideBottomUIMenu();  //隐藏虚拟按键，并且全屏
            AdShowUtils.getInstance().loadSplashAd(this,mSplashContainer, new AdShowUtils.SplashAdListener() {
                @Override
                public void jumpToMainScene() {
                    goToMainActivity();
                }
            });
        } else {
            goToMainActivity();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        mForceGoMain = true;
    }
    /**
     * 加载开屏广告
     */
    private void initViewAndData() {
        PixabayService service = RetrofitManager.getInstance()
                .getRetrofit()
                .create(PixabayService.class);
        mDisposable.add(service.getAppIdAdvertise(ApiAddress.WX_APP_ID)
                .compose(RxUtils.schedulersTransformer())
                .subscribe(privacyBean -> {
                    Log.d(TAG, "accept: " + privacyBean);
                    String startAdFlag = privacyBean.getResult().getStartAdFlag();
                    //NONE 无  CSJ 穿山甲  SYS 自系统
                    if ("NONE".equals(startAdFlag)) {
                    } else if ("CSJ".equals(startAdFlag)) {
                        MainApplication.getsInstance().isShowAd = true;
                    } else if ("SYS".equals(startAdFlag)) {
                    }
                    showPrivacyDialog();
                }, throwable -> Log.d(TAG, "loadMore: " + throwable)));

    }

    /**
     * 跳转到主页面
     */
    private void goToMainActivity() {
        Intent intent = new Intent(CsjSplashActivity.this, MainActivity.class);
        startActivity(intent);
        //mSplashContainer.removeAllViews();  //移除所有视图
        this.finish();
    }

    /**
     * 登录请求
     */
    private void Requestlogin() {
        PixabayService service = RetrofitManager.getInstance()
                .getRetrofit()
                .create(PixabayService.class);
/*      LoginBean.Param param = new LoginBean.Param();
        param.setAppId("wx348849nf4034nif132");
        param.setType(2);
        param.setUnionInfo(DeviceIdUtil.getDeviceUUID());*/
        //RequestBody body = RequestBody.create(MediaType.get("application/json; charset=utf-8"), new Gson().toJson(param));

        // {"appId":"wx348849nf4034nif132","type":2,"unionInfo":"ffffffff-a448-7504-ffff-ffffef05ac4a"}
        Map<String, Object> map = new HashMap<>();
        map.put("appId", "wx348849nf4034nif132");
        map.put("type", 2);
        map.put("unionInfo", DeviceIdUtil.getDeviceUUID());
        //{"param":{map}}
        Map<String, Object> param = new HashMap<>();
        param.put("param", map);
        RequestBody body = RequestBody.create(MediaType.get("application/json; charset=utf-8"), new Gson().toJson(param));
        mDisposable.add(service.login(body)// 添加rxjava请求到绑定容器
                .subscribeOn(Schedulers.io())// io线程执行请求
                .observeOn(AndroidSchedulers.mainThread())// 主线程返回结果
                .subscribe(new Consumer<BaseBean>() {
                    @Override
                    public void accept(BaseBean bean) throws Exception {
                        Log.e(TAG, "onResponse" + new Gson().toJson(bean));
                        //保存result_token
                        SharedPreferences sp = getApplicationContext().getSharedPreferences("sp", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString("result_token", bean.getResult()).apply();
                    }
                }, e -> Log.e(TAG, "onFailure" + e.getMessage())));
//        //另外一种请求方式
//        Call<BaseBean> call = service.login(body);
//        call.enqueue(new Callback<BaseBean>() {
//            @Override
//            public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
//                BaseBean bean = response.body();
//                Log.e(TAG, "onResponse" + new Gson().toJson(body));
//            }
//
//            @Override
//            public void onFailure(Call<BaseBean> call, Throwable t) {
//                Log.e(TAG, "onFailure" + t.getMessage());
//            }
//        });
    }


    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }
}
